<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>仪表板退出登录测试</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <style>
        body { background-color: #f8f9fa; }
        .test-container { max-width: 800px; margin: 2rem auto; }
        .test-box { background: white; padding: 2rem; border-radius: 10px; box-shadow: 0 2px 10px rgba(0,0,0,0.1); margin-bottom: 2rem; }
        iframe { width: 100%; height: 500px; border: 1px solid #ddd; border-radius: 5px; }
    </style>
</head>
<body>
    <div class="test-container">
        <h2>仪表板退出登录功能测试</h2>
        
        <div class="test-box">
            <h4>测试步骤</h4>
            <ol>
                <li>点击下方"自动登录"按钮先获取认证</li>
                <li>点击"在新窗口打开仪表板"查看仪表板页面</li>
                <li>在仪表板页面中点击任意"退出登录"按钮</li>
                <li>观察是否能成功退出并跳转到登录页面</li>
            </ol>
            
            <div class="mb-3">
                <button class="btn btn-primary" id="autoLoginBtn">自动登录</button>
                <button class="btn btn-success" id="openDashboardBtn">在新窗口打开仪表板</button>
                <button class="btn btn-warning" id="clearTokenBtn">清除Token</button>
                <button class="btn btn-info" id="checkTokenBtn">检查Token状态</button>
            </div>
            
            <div id="status" class="alert alert-info">等待操作...</div>
        </div>
        
        <div class="test-box">
            <h4>当前认证状态</h4>
            <div id="authInfo">
                <p><strong>Token:</strong> <span id="tokenDisplay">无</span></p>
                <p><strong>用户:</strong> <span id="userDisplay">无</span></p>
                <p><strong>状态:</strong> <span id="statusDisplay">未登录</span></p>
            </div>
        </div>
        
        <div class="test-box">
            <h4>操作日志</h4>
            <div id="logArea" style="background: #f8f9fa; padding: 1rem; border-radius: 5px; max-height: 300px; overflow-y: auto; font-family: monospace; font-size: 0.9rem;"></div>
        </div>
    </div>

    <script>
        function log(message, type = 'info') {
            const logArea = document.getElementById('logArea');
            const timestamp = new Date().toLocaleTimeString();
            const colors = {
                'info': '#0066cc',
                'success': '#28a745',
                'error': '#dc3545',
                'warning': '#ffc107'
            };
            
            logArea.innerHTML += `<div style="color: ${colors[type] || '#333'}">[${timestamp}] ${message}</div>`;
            logArea.scrollTop = logArea.scrollHeight;
        }
        
        function updateStatus(message, type = 'info') {
            const statusDiv = document.getElementById('status');
            statusDiv.className = `alert alert-${type}`;
            statusDiv.textContent = message;
        }
        
        function updateAuthInfo() {
            const token = localStorage.getItem('adminToken');
            const user = JSON.parse(localStorage.getItem('adminUser') || '{}');
            
            document.getElementById('tokenDisplay').textContent = token ? token.substring(0, 30) + '...' : '无';
            document.getElementById('userDisplay').textContent = user.real_name || user.username || '无';
            document.getElementById('statusDisplay').textContent = token ? '已登录' : '未登录';
        }
        
        async function autoLogin() {
            log('开始自动登录...', 'info');
            updateStatus('正在登录...', 'warning');
            
            try {
                const response = await fetch('/api/admin/login', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        username: 'admin',
                        password: 'newhand'
                    })
                });

                const result = await response.json();
                
                if (response.ok) {
                    log('登录成功！', 'success');
                    localStorage.setItem('adminToken', result.data.token);
                    localStorage.setItem('adminUser', JSON.stringify(result.data.user_info));
                    updateStatus('登录成功！现在可以打开仪表板测试退出功能', 'success');
                    updateAuthInfo();
                } else {
                    log(`登录失败: ${result.message}`, 'error');
                    updateStatus(`登录失败: ${result.message}`, 'error');
                }
            } catch (error) {
                log(`登录错误: ${error.message}`, 'error');
                updateStatus(`登录错误: ${error.message}`, 'error');
            }
        }
        
        function openDashboard() {
            const token = localStorage.getItem('adminToken');
            if (!token) {
                updateStatus('请先登录', 'error');
                return;
            }
            
            log('在新窗口打开仪表板...', 'info');
            window.open('/admin/dashboard.html', '_blank');
            updateStatus('已在新窗口打开仪表板，请在新窗口中测试退出登录功能', 'info');
        }
        
        function clearToken() {
            localStorage.removeItem('adminToken');
            localStorage.removeItem('adminUser');
            log('已清除Token', 'warning');
            updateStatus('Token已清除', 'warning');
            updateAuthInfo();
        }
        
        function checkToken() {
            const token = localStorage.getItem('adminToken');
            if (token) {
                try {
                    const payload = JSON.parse(atob(token.split('.')[1]));
                    const now = Math.floor(Date.now() / 1000);
                    
                    log(`Token信息: 用户ID=${payload.id}, 用户名=${payload.username}, 角色=${payload.role}`, 'info');
                    
                    if (payload.exp && payload.exp < now) {
                        log('Token已过期！', 'error');
                        updateStatus('Token已过期', 'error');
                    } else {
                        log('Token仍然有效', 'success');
                        updateStatus('Token有效', 'success');
                    }
                } catch (e) {
                    log('无法解析Token', 'error');
                    updateStatus('Token格式错误', 'error');
                }
            } else {
                log('没有找到Token', 'warning');
                updateStatus('未登录', 'warning');
            }
            updateAuthInfo();
        }
        
        // 页面加载时初始化
        document.addEventListener('DOMContentLoaded', function() {
            updateAuthInfo();
            log('测试工具已加载', 'info');
            
            // 绑定事件
            document.getElementById('autoLoginBtn').addEventListener('click', autoLogin);
            document.getElementById('openDashboardBtn').addEventListener('click', openDashboard);
            document.getElementById('clearTokenBtn').addEventListener('click', clearToken);
            document.getElementById('checkTokenBtn').addEventListener('click', checkToken);
            
            // 监听storage变化（当在其他窗口登录/退出时更新显示）
            window.addEventListener('storage', function(e) {
                if (e.key === 'adminToken' || e.key === 'adminUser') {
                    updateAuthInfo();
                    if (e.key === 'adminToken' && !e.newValue) {
                        log('检测到在其他窗口退出登录', 'info');
                        updateStatus('检测到在其他窗口退出登录', 'info');
                    }
                }
            });
        });
    </script>
</body>
</html> 